﻿using DocumentFormat.OpenXml.Drawing;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Data.SqlClient;
using NP.BPMReportPlatform.BPMPlatform;
using NP.BPMReportPlatform.DBHelper;
using NP.BPMReportPlatform.Entities.BPM_Business;
using NP.BPMReportPlatform.Entities.BPM_Business.CommonReportConfigs;
using NP.BPMReportPlatform.Entities.BPM_Business.ThirdFlow;
using NP.BPMReportPlatform.Reports.CommonReportConfigs.Dtos;
using NP.BPMReportPlatform.Reports.CXYXTHNRA.Dtos;
using NP.BPMReportPlatform.Utils;
using RazorEngine.Compilation.ImpromptuInterface.InvokeExt;
using Scriban;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.Application.Dtos;
using Volo.Abp.Domain.Entities;

namespace NP.BPMReportPlatform.Reports.CommonReportConfigs
{
    public class CommonReportConfigsService : BPMReportPlatformAppService, ICommonReportConfigsService
    {
        private readonly SqlSugarClient _db, _dbPlatform, _dbProcess, _dbEngine, _dbToDoCenter;
        private readonly IBPMUtilsAppService _bPMUtilsApp;
        private readonly IBPMPlatformAppService _iBPMPlatformApp;
        public CommonReportConfigsService(ISqlSugarAppService sqlSugarAppService, IBPMUtilsAppService bPMUtilsApp,
            IBPMPlatformAppService iBPMPlatformApp)
        {
            _db = sqlSugarAppService.GetBusinessInstance();
            _dbPlatform = sqlSugarAppService.GetPlatformInstance();
            _bPMUtilsApp = bPMUtilsApp;
            _dbProcess = sqlSugarAppService.GetProcessInstance();
            _dbEngine = sqlSugarAppService.GetEngineInstance();
            _dbToDoCenter = sqlSugarAppService.GetToDoCenterInstance();
            _iBPMPlatformApp = iBPMPlatformApp;
        }

        #region page

        public async Task<PagedResultDto<CommonReportPage>> GetAllPageAsync(CommonReportPageInput input)
        {
            RefAsync<int> totalCount = 0;

            var listQueryable = GetQueryablePage(input);
            var listViewDto = await listQueryable.ToPageListAsync(input.PageIndex, input.PageSize, totalCount);

            //返回结果
            return new PagedResultDto<CommonReportPage>()
            {
                TotalCount = totalCount,
                Items = listViewDto
            };
        }

        private ISugarQueryable<CommonReportPage> GetQueryablePage(CommonReportPageInput input)
        {
            var listQueryable = _db.Queryable<CommonReportPage>()
                .WhereIF(!string.IsNullOrEmpty(input.PageCode), x => x.PageCode.Contains(input.PageCode))
                .WhereIF(!string.IsNullOrEmpty(input.PageName), x => x.PageName.Contains(input.PageName))
                .WhereIF(!string.IsNullOrEmpty(input.TableName), x => x.TableName.Contains(input.TableName))
                .WhereIF(input.IsEnabled != null, x => x.IsEnabled == input.IsEnabled)
                .WhereIF(input.PageType != null, x => x.PageType == input.PageType)
                .OrderBy(x => x.CreateTime, OrderByType.Desc);

            return listQueryable;
        }

        public async Task AddOrUpdatePage(UpdateCommonReportPageInput input)
        {
            var userId = await _iBPMPlatformApp.GetUserAsync(CurrentUser.UserName);
            if (!string.IsNullOrEmpty(input.Id))
            {
                var entity = await _db.Queryable<CommonReportPage>().FirstAsync(x => x.Id == input.Id);
                if (entity == null)
                {
                    throw new Exception("数据未找到");
                }

                var isExsit = await _db.Queryable<CommonReportPage>().AnyAsync(x => x.PageCode == input.PageCode && x.Id != input.Id);
                if (isExsit)
                {
                    throw new Exception("页面编码已存在");
                }

                entity.PageCode = string.IsNullOrEmpty(input.PageCode) ? Guid.NewGuid().ToString() : input.PageCode;
                entity.PageName = input.PageName;
                entity.IsEnabled = input.IsEnabled;
                entity.PageType = input.PageType;
                entity.DbName = input.DbName;
                entity.TableName = input.TableName;
                entity.UpdateUserId = userId;
                entity.UpdateTime = DateTime.Now;

                await _db.Updateable(entity).ExecuteCommandAsync();
            }
            else
            {
                var isExsit = await _db.Queryable<CommonReportPage>().AnyAsync(x => x.PageCode == input.PageCode);
                if (isExsit)
                {
                    throw new Exception("页面编码已存在");
                }

                var entity = new CommonReportPage
                {
                    Id = Guid.NewGuid().ToString(),
                    PageCode = string.IsNullOrEmpty(input.PageCode) ? Guid.NewGuid().ToString() : input.PageCode,
                    PageName = input.PageName,
                    IsEnabled = input.IsEnabled,
                    PageType = input.PageType,
                    DbName = input.DbName,
                    TableName = input.TableName,
                    CreateUserId = userId,
                    CreateTime = DateTime.Now
                };

                await _db.Insertable(entity).ExecuteCommandAsync();

                input.Id = entity.Id;
            }

            await InitTable(new CommonReportInitTableInput { TableName = input.TableName, DBName = input.DbName, PageId = input.Id });
        }

        public async Task DeletePage(DeleteCommonReportInput input)
        {
            if (string.IsNullOrEmpty(input.Id))
            {
                throw new Exception("数据未找到");
            }

            var entity = await _db.Queryable<CommonReportPage>().FirstAsync(x => x.Id == input.Id);
            if (entity == null)
            {
                throw new Exception("数据未找到");
            }

            await _db.Deleteable<CommonReportPage>().Where(x => x.Id == input.Id).ExecuteCommandAsync();
        }

        public async Task BindPageModule(BindPageModuleInput input)
        {
            var userId = await _iBPMPlatformApp.GetUserAsync(CurrentUser.UserName);
            var convertStrInputIds = input.BindList.Select(x => x.PageId.ToString() + x.ModuleId.ToString()).ToList();
            var exsit = await _db.Queryable<CommonReportPageModule>().AnyAsync(x =>
                SqlFunc.ContainsArray(convertStrInputIds,
                SqlFunc.MergeString(SqlFunc.ToString(x.PageId), SqlFunc.ToString(x.ModuleId))));
            if (exsit)
            {
                throw new Exception("绑定关系已存在");
            }

            var insertEntities = new List<CommonReportPageModule>();
            foreach(var item in input.BindList)
            {
                insertEntities.Add(new CommonReportPageModule
                {
                    Id = Guid.NewGuid().ToString(),
                    PageId = item.PageId,
                    ModuleId = item.ModuleId,
                    CreateTime = DateTime.Now,
                    CreateUserId = userId,
                });
            }
            await _db.Insertable(insertEntities).ExecuteCommandAsync();
        }

        public async Task DeletePageModule(DeletePageModuleInput input)
        {
            if (input.Ids == null || !input.Ids.Any())
            {
                throw new Exception("未获取到入参");
            }

            await _db.Deleteable<CommonReportPageModule>().Where(x => input.Ids.Contains(x.Id)).ExecuteCommandAsync();
        }

        #endregion

        #region module

        public async Task<PagedResultDto<CommonReportModule>> GetAllModuleAsync(CommonReportModuleInput input)
        {
            RefAsync<int> totalCount = 0;

            var listQueryable = GetQueryableModule(input);
            var listViewDto = await listQueryable.ToPageListAsync(input.PageIndex, input.PageSize, totalCount);

            //返回结果
            return new PagedResultDto<CommonReportModule>()
            {
                TotalCount = totalCount,
                Items = listViewDto
            };
        }

        private ISugarQueryable<CommonReportModule> GetQueryableModule(CommonReportModuleInput input)
        {
            var listQueryable = _db.Queryable<CommonReportModule, CommonReportPageModule>(
                (x, c) => new JoinQueryInfos(JoinType.Left, x.Id == c.ModuleId))
                .WhereIF(!string.IsNullOrEmpty(input.PageId), (x, c) => c.PageId == input.PageId)
                .WhereIF(!string.IsNullOrEmpty(input.ModuleName), (x, c) => x.ModuleName.Contains(input.ModuleName))
                .WhereIF(!string.IsNullOrEmpty(input.ModuleType), (x, c) => x.ModuleType == input.ModuleType)
                .WhereIF(input.IsEnabled != null, (x, c) => x.IsEnabled == input.IsEnabled)
                .OrderBy(x => x.CreateTime, OrderByType.Desc);

            return listQueryable;
        }

        public async Task AddOrUpdateModule(UpdateCommonReportModuleInput input)
        {
            var userId = await _iBPMPlatformApp.GetUserAsync(CurrentUser.UserName);
            if (!string.IsNullOrEmpty(input.Id))
            {
                var entity = await _db.Queryable<CommonReportModule>().FirstAsync(x => x.Id == input.Id);
                if (entity == null)
                {
                    throw new Exception("数据未找到");
                }

                entity.ModuleName = input.ModuleName;
                entity.ModuleWidth = input.ModuleWidth;
                entity.ModuleHeight = input.ModuleHeight;
                entity.ModuleType = input.ModuleType;
                entity.ShowType = input.ShowType;
                entity.IsEnabled = input.IsEnabled;
                entity.ReportType = input.ReportType;
                entity.AuthCode = input.AuthCode;
                entity.UpdateUserId = userId;
                entity.UpdateTime = DateTime.Now;

                await _db.Updateable(entity).ExecuteCommandAsync();
            }
            else
            {
                var entity = new CommonReportModule
                {
                    Id = Guid.NewGuid().ToString(),
                    ModuleName = input.ModuleName,
                    ModuleWidth = input.ModuleWidth,
                    ModuleHeight = input.ModuleHeight,
                    ModuleType = input.ModuleType,
                    ShowType = input.ShowType,
                    IsEnabled = input.IsEnabled,
                    ReportType = input.ReportType,
                    AuthCode = input.AuthCode,
                    CreateUserId = userId,
                    CreateTime = DateTime.Now
                };

                await _db.Insertable(entity).ExecuteCommandAsync();

                if (!string.IsNullOrEmpty(input.PageId) && _db.Queryable<CommonReportPage>().Any(x => x.Id == input.PageId))
                {
                    if (!_db.Queryable<CommonReportPageModule>().Any(x => x.ModuleId == entity.Id && x.PageId == input.PageId))
                    {
                        await _db.Insertable(new CommonReportPageModule
                        {
                            Id = Guid.NewGuid().ToString(),
                            ModuleId = entity.Id,
                            PageId = input.PageId,
                            CreateTime = DateTime.Now,
                            CreateUserId = userId,
                        }).ExecuteCommandAsync();
                    }
                }
            }
        }

        public async Task DeleteModule(DeleteCommonReportInput input)
        {
            if (string.IsNullOrEmpty(input.Id))
            {
                throw new Exception("数据未找到");
            }

            var entity = await _db.Queryable<CommonReportModule>().FirstAsync(x => x.Id == input.Id);
            if (entity == null)
            {
                throw new Exception("数据未找到");
            }

            await _db.Deleteable<CommonReportModule>().Where(x => x.Id == input.Id).ExecuteCommandAsync();
            await _db.Deleteable<CommonReportFieldConfig>().Where(x => x.ModuleId == input.Id).ExecuteCommandAsync();
            await _db.Deleteable<CommonReportPageModule>().Where(x => x.ModuleId == input.Id).ExecuteCommandAsync();
            await _db.Deleteable<CommonReportCustomScripts>().Where(x=>x.ModuleId == input.Id).ExecuteCommandAsync();
        }

        #endregion

        #region field

        public async Task<PagedResultDto<CommonReportFieldConfig>> GetAllFieldAsync(CommonReportFieldInput input)
        {
            RefAsync<int> totalCount = 0;

            var listQueryable = GetQueryableField(input);
            var listViewDto = await listQueryable.ToPageListAsync(input.PageIndex, input.PageSize, totalCount);

            //返回结果
            return new PagedResultDto<CommonReportFieldConfig>()
            {
                TotalCount = totalCount,
                Items = listViewDto
            };
        }

        private ISugarQueryable<CommonReportFieldConfig> GetQueryableField(CommonReportFieldInput input)
        {
            var listQueryable = _db.Queryable<CommonReportFieldConfig>()
                .WhereIF(input.ModuleId != null, x => x.ModuleId == input.ModuleId)
                .WhereIF(!string.IsNullOrEmpty(input.InputBoxType), x => x.InputBoxType.Contains(input.InputBoxType))
                .WhereIF(!string.IsNullOrEmpty(input.FieldName), x => x.FieldName.Contains(input.FieldName))
                .OrderBy(x => x.ShowIndex);

            return listQueryable;
        }

        public async Task AddOrUpdateField(UpdateCommonReportFieldInput input)
        {
            var userId = await _iBPMPlatformApp.GetUserAsync(CurrentUser.UserName);

            var fields = await GetFieldsByModuleId(input.ModuleId);
            if (!fields.Any())
            {
                throw new Exception("没有绑定数据表");
            }

            var dbName = fields.First().TABLE_SCHEMA;
            var tableName = fields.First().TABLE_NAME;

            if (!string.IsNullOrEmpty(input.Id))
            {
                var entity = await _db.Queryable<CommonReportFieldConfig>().FirstAsync(x => x.Id == input.Id);
                if (entity == null)
                {
                    throw new Exception("数据未找到");
                }

                if (_db.Queryable<CommonReportFieldConfig>().Any(x => 
                    x.ModuleId == entity.ModuleId && x.FieldName == input.FieldName && x.Id != entity.Id))
                {
                    throw new Exception("字段已存在");
                }
                if (_db.Queryable<CommonReportFieldConfig>().Any(x =>
                    x.ModuleId == entity.ModuleId && x.FieldDesc == input.FieldDesc && x.Id != entity.Id))
                {
                    throw new Exception("字段描述已存在");
                }

                entity.ModuleId = input.ModuleId;
                entity.FieldName = input.FieldName;
                entity.FieldDesc = input.FieldDesc;
                entity.ShortSelectItemJson = input.ShortSelectItemJson;
                entity.InputBoxType = input.InputBoxType;
                entity.ColumnWidth = input.ColumnWidth;
                entity.InputBoxWidth = input.InputBoxWidth;
                entity.InputBoxHeight = input.InputBoxHeight;
                entity.IsCanEdit = input.IsCanEdit;
                entity.IsRequired = input.IsRequired;
                entity.IsSearchItem = input.IsSearchItem;
                entity.IsShow = input.IsShow;
                entity.IsCanExport = input.IsCanExport;
                entity.IsCanImport = input.IsCanImport;
                entity.ShowIndex = input.ShowIndex;
                entity.CustomScript = input.CustomScript;
                entity.IsAccurate = input.IsAccurate;
                entity.OrderType = input.OrderType;
                entity.OrderIndex = input.OrderIndex;
                entity.CheckType = input.CheckType;
                entity.RegexContent = input.RegexContent;
                entity.CheckFailMessage = input.CheckFailMessage;
                entity.DefaultType = input.DefaultType;
                entity.DefaultValue = input.DefaultValue;
                entity.UpdateUserId = userId;
                entity.UpdateTime = DateTime.Now;

                await _db.Updateable(entity).ExecuteCommandAsync();
            }
            else
            {
                if (_db.Queryable<CommonReportFieldConfig>().Any(x =>
                    x.ModuleId == input.ModuleId && x.FieldName == input.FieldName))
                {
                    throw new Exception("字段已存在");
                }
                if (_db.Queryable<CommonReportFieldConfig>().Any(x =>
                    x.ModuleId == input.ModuleId && x.FieldDesc == input.FieldDesc))
                {
                    throw new Exception("字段描述已存在");
                }

                var entity = new CommonReportFieldConfig
                {
                    Id = Guid.NewGuid().ToString(),
                    ModuleId = input.ModuleId,
                    FieldName = input.FieldName,
                    FieldDesc = input.FieldDesc,
                    ShortSelectItemJson = input.ShortSelectItemJson,
                    InputBoxType = input.InputBoxType,
                    ColumnWidth = input.ColumnWidth,
                    InputBoxWidth = input.InputBoxWidth,
                    InputBoxHeight = input.InputBoxHeight,
                    IsCanEdit = input.IsCanEdit,
                    IsRequired = input.IsRequired,
                    IsSearchItem = input.IsSearchItem,
                    IsShow = input.IsShow,
                    IsCanExport = input.IsCanExport,
                    IsCanImport = input.IsCanImport,
                    ShowIndex = input.ShowIndex,
                    CustomScript = input.CustomScript,
                    IsAccurate = input.IsAccurate,
                    OrderType = input.OrderType,
                    OrderIndex = input.OrderIndex,
                    CheckType = input.CheckType,
                    RegexContent = input.RegexContent,
                    CheckFailMessage = input.CheckFailMessage,
                    DefaultType = input.DefaultType,
                    DefaultValue = input.DefaultValue,
                    CreateUserId = userId,
                    CreateTime = DateTime.Now,
                };

                await _db.Insertable(entity).ExecuteCommandAsync();
            }
        }

        private async Task<List<CommonReportField>> GetFieldsByModuleId(string moduleId)
        {
            var res = new List<CommonReportField>();
            if (string.IsNullOrEmpty(moduleId))
            {
                return res;
            }
            var page = await _db.Queryable<CommonReportPage, CommonReportPageModule>((a, b) => a.Id == b.PageId)
                .Where((a, b) => b.ModuleId == moduleId).Select((a, b) => a).FirstAsync();
            if (page == null)
            {
                return res;
            }

            return await _db.Queryable<CommonReportField>().Where(x => x.TABLE_SCHEMA == page.DbName && x.TABLE_NAME == page.TableName).ToListAsync();
        }

        public async Task DeleteField(DeleteCommonReportInput input)
        {
            if (string.IsNullOrEmpty(input.Id))
            {
                throw new Exception("数据未找到");
            }

            var entity = await _db.Queryable<CommonReportFieldConfig>().FirstAsync(x => x.Id == input.Id);
            if (entity == null)
            {
                throw new Exception("数据未找到");
            }

            await _db.Deleteable<CommonReportFieldConfig>().Where(x => x.Id == input.Id).ExecuteCommandAsync();
        }

        /// <summary>
        /// 初始化表属性数据
        /// </summary>
        public async Task<List<CommonReportField>> InitTable(CommonReportInitTableInput input)
        {
            if (string.IsNullOrEmpty(input.DBName) || string.IsNullOrEmpty(input.TableName))
            {
                throw new Exception("参数缺失");
            }

            var userId = await _iBPMPlatformApp.GetUserAsync(CurrentUser.UserName);
            var sql = $@"
                SELECT 
	                TABLE_SCHEMA,
	                TABLE_NAME,
                    COLUMN_NAME, 
                    ORDINAL_POSITION,
                    DATA_TYPE, 
                    IS_NULLABLE, 
                    COLUMN_DEFAULT, 
                    CHARACTER_MAXIMUM_LENGTH, 
                    NUMERIC_PRECISION, 
                    NUMERIC_SCALE, 
                    DATETIME_PRECISION, 
                    COLUMN_TYPE, 
                    COLUMN_KEY, 
                    EXTRA,
	                COLUMN_COMMENT
                FROM 
                    INFORMATION_SCHEMA.COLUMNS
                WHERE 
                    TABLE_SCHEMA = @dbName AND 
                    TABLE_NAME = @tableName;";
            var sqlParameters = new List<SugarParameter>
            {
                new SugarParameter("@dbName", input.DBName),
                new SugarParameter("@tableName", input.TableName)
            };
            var query = await _db.Ado.SqlQueryAsync<CommonReportField>(sql, sqlParameters);
            if (query.Count > 0)
            {
                var exsitDatas = _db.Queryable<CommonReportField>().Where(
                    x => x.TABLE_SCHEMA == input.DBName && x.TABLE_NAME == input.TableName).ToList();
                if (exsitDatas.Any())
                {
                    _db.Deleteable(exsitDatas).ExecuteCommand();
                }

                query.ForEach(x =>
                {
                    x.Id = Guid.NewGuid().ToString();
                    x.CreateTime = DateTime.Now;
                    x.CreateUserId = userId;
                });

                _db.Insertable(query).ExecuteCommand();

                if (!string.IsNullOrEmpty(input.PageId))
                {
                    var searchModuelFields = new List<CommonReportFieldConfig>();
                    if (input.ModuleType == "2")
                    {
                        searchModuelFields = await GetRelationFieldConfigsAsync(input.PageId, "3");
                    }
                    else if(input.ModuleType == "3")
                    {
                        searchModuelFields = await GetRelationFieldConfigsAsync(input.PageId, "2");
                    }
                    else if(input.ModuleType == "6")
                    {
                        searchModuelFields = await GetRelationFieldConfigsAsync(input.PageId, "1");
                    }
                    else if (input.ModuleType == "7")
                    {
                        searchModuelFields = await GetRelationFieldConfigsAsync(input.PageId, "2");
                        if (!searchModuelFields.Any())
                        {
                            await GetRelationFieldConfigsAsync(input.PageId, "3");
                        }
                    }

                    if (!searchModuelFields.Any() && input.ModuleType != "6")
                    {
                        searchModuelFields = await GetRelationFieldConfigsAsync(input.PageId, "1");
                    }

                    if (searchModuelFields.Any())
                    {
                        query.ForEach(x =>
                        {
                            var field = searchModuelFields.FirstOrDefault(q => q.FieldName == x.COLUMN_NAME);
                            x.FieldDesc = field?.FieldDesc ?? "";
                            x.InputBoxType = field?.InputBoxType ?? "";
                            x.ShortSelectItemJson = field?.ShortSelectItemJson ?? "";
                            x.ShowIndex = field?.ShowIndex ?? 0;
                            x.CheckType = field?.CheckType;
                            x.RegexContent = field?.RegexContent;
                            x.CheckFailMessage = field?.CheckFailMessage;
                            x.DefaultType = field?.DefaultType;
                            x.DefaultValue = field?.DefaultValue;
                        });
                    }
                }

                return query.OrderBy(x => x.ORDINAL_POSITION).ToList();
            }
            else
            {
                throw new Exception("未找到表数据");
            }
        }

        private async Task<List<CommonReportFieldConfig>> GetRelationFieldConfigsAsync(string PageId, string ModuleType)
        {
            if (string.IsNullOrWhiteSpace(PageId) || string.IsNullOrWhiteSpace(ModuleType))
            {
                return new List<CommonReportFieldConfig>();
            }
            return await _db.Queryable<CommonReportModule, CommonReportPageModule, CommonReportFieldConfig>(
                (a, b, c) => a.Id == b.ModuleId && a.Id == c.ModuleId)
                .Where((a, b, c) => b.PageId == PageId && a.ModuleType == ModuleType).Select((a, b, c) => c).ToListAsync();
        }

        /// <summary>
        /// 批量添加字段
        /// </summary>
        /// <param name="inputs"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public async Task BatchAddFields(BatchAddCommonReportFieldInput inputs)
        {
            if (!inputs.BatchAddFields.Any())
            {
                throw new Exception("参数错误");
            }

            var userId = await _iBPMPlatformApp.GetUserAsync(CurrentUser.UserName);
            var insertEntities = new List<CommonReportFieldConfig>();
            var updateEntities = new List<CommonReportFieldConfig>();
            foreach (var input in inputs.BatchAddFields)
            {
                if (inputs.BatchAddFields.Count(x => x.FieldName == input.FieldName) > 1)
                {
                    throw new Exception($"{input.FieldName}字段重复");
                }
                if (inputs.BatchAddFields.Count(x => x.FieldDesc == input.FieldDesc) > 1)
                {
                    throw new Exception($"{input.FieldDesc}字段描述重复");
                }

                if (!string.IsNullOrEmpty(input.Id))
                {
                    var entity = await _db.Queryable<CommonReportFieldConfig>().FirstAsync(x => x.Id == input.Id);
                    if (entity == null)
                    {
                        throw new Exception("数据未找到");
                    }

                    if (_db.Queryable<CommonReportFieldConfig>().Any(x =>
                        x.ModuleId == entity.ModuleId && x.FieldName == input.FieldName && x.Id != entity.Id))
                    {
                        throw new Exception($"{input.FieldName}字段已存在");
                    }
                    if (_db.Queryable<CommonReportFieldConfig>().Any(x =>
                        x.ModuleId == entity.ModuleId && x.FieldDesc == input.FieldDesc && x.Id != entity.Id))
                    {
                        throw new Exception($"{input.FieldDesc}字段描述已存在");
                    }

                    entity.ModuleId = input.ModuleId;
                    entity.FieldName = input.FieldName;
                    entity.FieldDesc = input.FieldDesc;
                    entity.ShortSelectItemJson = input.ShortSelectItemJson;
                    entity.InputBoxType = input.InputBoxType;
                    entity.ColumnWidth = input.ColumnWidth;
                    entity.InputBoxWidth = input.InputBoxWidth;
                    entity.InputBoxHeight = input.InputBoxHeight;
                    entity.IsCanEdit = input.IsCanEdit;
                    entity.IsRequired = input.IsRequired;
                    entity.IsSearchItem = input.IsSearchItem;
                    entity.IsShow = input.IsShow;
                    entity.IsCanExport = input.IsCanExport;
                    entity.IsCanImport = input.IsCanImport;
                    entity.ShowIndex = input.ShowIndex;
                    entity.CustomScript = input.CustomScript;
                    entity.IsAccurate = input.IsAccurate;
                    entity.OrderType = input.CustomScript;
                    entity.OrderIndex = input.OrderIndex;
                    entity.CheckType = input.CheckType;
                    entity.RegexContent = input.RegexContent;
                    entity.CheckFailMessage = input.CheckFailMessage;
                    entity.DefaultType = input.DefaultType;
                    entity.DefaultValue = input.DefaultValue;
                    entity.UpdateUserId = userId;
                    entity.UpdateTime = DateTime.Now;

                    updateEntities.Add(entity);
                }
                else
                {
                    if (_db.Queryable<CommonReportFieldConfig>().Any(x =>
                        x.ModuleId == input.ModuleId && x.FieldName == input.FieldName))
                    {
                        throw new Exception($"{input.FieldName}字段已存在");
                    }
                    if (_db.Queryable<CommonReportFieldConfig>().Any(x =>
                        x.ModuleId == input.ModuleId && x.FieldDesc == input.FieldDesc))
                    {
                        throw new Exception($"{input.FieldDesc}字段描述已存在");
                    }

                    var entity = new CommonReportFieldConfig
                    {
                        Id = Guid.NewGuid().ToString(),
                        ModuleId = input.ModuleId,
                        FieldName = input.FieldName,
                        FieldDesc = input.FieldDesc,
                        ShortSelectItemJson = input.ShortSelectItemJson,
                        InputBoxType = input.InputBoxType,
                        ColumnWidth = input.ColumnWidth,
                        InputBoxWidth = input.InputBoxWidth,
                        InputBoxHeight = input.InputBoxHeight,
                        IsCanEdit = input.IsCanEdit,
                        IsRequired = input.IsRequired,
                        IsSearchItem = input.IsSearchItem,
                        IsShow = input.IsShow,
                        IsCanExport = input.IsCanExport,
                        IsCanImport = input.IsCanImport,
                        ShowIndex = input.ShowIndex,
                        CreateUserId = userId,
                        CreateTime = DateTime.Now,
                        CustomScript = input.CustomScript,
                        IsAccurate = input.IsAccurate,
                        OrderType = input.CustomScript,
                        OrderIndex = input.OrderIndex,
                        CheckType = input.CheckType,
                        RegexContent = input.RegexContent,
                        CheckFailMessage = input.CheckFailMessage,
                        DefaultType = input.DefaultType,
                        DefaultValue = input.DefaultValue,
                    };

                    insertEntities.Add(entity);
                }
            }

            if (updateEntities.Any() || insertEntities.Any())
            {
                try
                {
                    _db.BeginTran();

                    if (updateEntities.Any())
                    {
                        await _db.Updateable(updateEntities).ExecuteCommandAsync();
                    }
                    if (insertEntities.Any())
                    {
                        await _db.Insertable(insertEntities).ExecuteCommandAsync();
                    }

                    _db.CommitTran();
                }
                catch (Exception ex)
                {
                    _db.RollbackTran();

                    throw new Exception(ex.Message);
                }
            }
        }

        /// <summary>
        /// 获取校验配置项
        /// </summary>
        /// <returns></returns>
        public async Task<List<CommonReportCheckConfigs>> GetCheckConfigs()
        {
            return await _db.Queryable<CommonReportCheckConfigs>().OrderBy(x => x.OrderIndex).ToListAsync();
        }

        #endregion

        #region scripts

        public async Task<PagedResultDto<CommonReportCustomScripts>> GetAllScriptAsync(CommonReportCustomScriptsInput input)
        {
            RefAsync<int> totalCount = 0;

            var listQueryable = GetQueryableScript(input);
            var listViewDto = await listQueryable.ToPageListAsync(input.PageIndex, input.PageSize, totalCount);

            //返回结果
            return new PagedResultDto<CommonReportCustomScripts>()
            {
                TotalCount = totalCount,
                Items = listViewDto
            };
        }

        private ISugarQueryable<CommonReportCustomScripts> GetQueryableScript(CommonReportCustomScriptsInput input)
        {
            var listQueryable = _db.Queryable<CommonReportCustomScripts>()
                .WhereIF(!string.IsNullOrEmpty(input.ModuleId), x => x.ModuleId == input.ModuleId)
                .WhereIF(input.ScriptType != null, x => x.ScriptType == input.ScriptType)
                .OrderBy(x => x.CreateTime, OrderByType.Desc);

            return listQueryable;
        }

        public async Task AddOrUpdateScript(UpdateCommonReportCustomScriptsInput input)
        {
            var userId = await _iBPMPlatformApp.GetUserAsync(CurrentUser.UserName);
            if (!string.IsNullOrEmpty(input.Id))
            {
                var entity = await _db.Queryable<CommonReportCustomScripts>().FirstAsync(x => x.Id == input.Id);
                if (entity == null)
                {
                    throw new Exception("数据未找到");
                }

                entity.CustomScript = input.CustomScript;
                entity.ScriptType = input.ScriptType;
                entity.Message = input.Message;
                entity.UpdateUserId = userId;
                entity.UpdateTime = DateTime.Now;

                await _db.Updateable(entity).ExecuteCommandAsync();
            }
            else
            {
                var entity = new CommonReportCustomScripts
                {
                    Id = Guid.NewGuid().ToString(),
                    ModuleId= input.ModuleId,
                    CustomScript = input.CustomScript,
                    ScriptType = input.ScriptType,
                    Message = input.Message,
                    CreateUserId = userId,
                    CreateTime = DateTime.Now
                };

                await _db.Insertable(entity).ExecuteCommandAsync();
            }
        }

        public async Task DeleteScript(DeleteCommonReportInput input)
        {
            if (string.IsNullOrEmpty(input.Id))
            {
                throw new Exception("数据未找到");
            }

            var entity = await _db.Queryable<CommonReportCustomScripts>().FirstAsync(x => x.Id == input.Id);
            if (entity == null)
            {
                throw new Exception("数据未找到");
            }

            await _db.Deleteable<CommonReportCustomScripts>().Where(x => x.Id == input.Id).ExecuteCommandAsync();
        }

        #endregion
    }
}
